#!/bin/bash

app="hypnos-did"
cmd="go build"
os=""
env=""
out=$app
rel=false
linux=false
deploy=false
gofile=""

usage() {
    # display help
    echo -e "Usage: $0 [OPTIONS] [gofile...]"
    echo -e "\t-h  display help info."
    echo -e "\t-l  build for linux with default params."
    echo -e "\t-c  clear output path first."
    echo -e "\t-o  output execute file name."
    echo -e "\t-s  for which os."
    echo -e "\t-r  upx to reduce output size."
    echo -e "\t-d  deploy and restart."
    echo -e "For example: ./build.sh -o moat -s linux"
    exit 1
}

exec_cmd() {
    echo $*
    $*
}

check_cmd() {
    type $1 >/dev/null 2>&1 || { echo >&2 "$1 required but it's not installed.  Aborting."; exit 1; }
}

clear_output() {
    exec_cmd "rm -rf output"
}

upx_output() {
    if $rel; then
        check_cmd "upx"
        exec_cmd "upx $*"
    fi
}

deploy_and_restart() {
    if $deploy; then
        dpath=$*
        dname=${dpath##*/}
        auto_scp zx-SecCam!#% $dpath root@54.215.155.225:/root/zx_app_server
        auto_smart_ssh zx-SecCam!#% root@54.215.155.225 "cd /root/zx_app_server; ./run.sh $dname -restart > /dev/null 2>&1"
    fi
}

build_for_linux() {
    # out="./output/${app}_linux"
    out="./output/${app}"
    cmd="env GOOS=linux $cmd -o $out"
    exec_cmd $cmd
    upx_output $out
    deploy_and_restart $out
    exit 1
}

auto_scp () {
    expect -c "set timeout -1;
        spawn scp -o StrictHostKeyChecking=no ${@:2};
        expect {
            *assword:* {send -- $1\r;
                expect {
                    *denied* {exit 1;}
                    eof
                }
            }
            eof {exit 1;}
        }
    "
    return $?
}

auto_smart_ssh () {
    expect -c "set timeout -1;
        spawn ssh -f -n -o StrictHostKeyChecking=no $2 \"${@:3}\";
            expect {
                *assword:* {send -- $1\r;
                     expect {
                        *denied* {exit 2;}
                        eof
                     }
                }
                eof {exit 1;}
            }
    "
    return $?
}

parse_params() {
    # parsing params
    while getopts "hcro:s:ld" arg;
    do
        case $arg in
        h)
            usage
            ;;
        l)
            linux=true
            ;;
        c)
            clear_output
            ;;
        r)
            rel=true
            ;;
        o)
            out="$OPTARG"
            ;;
        s)
            os="$OPTARG"
            ;;
        d)
            deploy=true
            ;;
        ?)
            usage
            ;;
        esac
    done

    shift $((OPTIND-1))
    gofile="$@"
}

parse_params $@

if $linux; then
    os="linux"
fi

# combining command
if [ -n "$os" ]; then
    env="GOOS=$os"
    # out="${out}_$os"
    out="${out}"
fi

if [ -n "$env" ]; then
    env="env $env"
fi
if [ -n "$out" ]; then
    out="./output/$out"
fi

# executing command
exec_cmd "$env $cmd -o $out $gofile"
upx_output "$out"
deploy_and_restart "$out"
exit 0